94. 二叉树的中序遍历
为保证权益,题目请参考 94. 二叉树的中序遍历(From LeetCode).
解决方案1
Python
python
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
##############################################################################
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
stacks=[]
r = root
while len(stacks) !=0 or r is not None:
while r is not None:
stacks.append(r)
r = r.left
r = stacks.pop()
ans.append(r.val)
r = r.right
return ans
##############################################################################
def runTest():
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.right = b
b.left = c
so = Solution()
print(so.inorderTraversal(a))
runTest()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40